<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryData.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          node-key="id"
          :expand-on-click-node="false"
          default-expand-all
          highlight-current
          :data="depts"
          :props="{label:'name'}"
          @current-change="treeChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="$refs.iptExcel.showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="excelExport">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list" style="width: 100%">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template slot-scope="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template slot-scope="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="openAssignRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确定删除吗？"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            :current-page.sync="queryData.page"
            :page-size="queryData.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @current-change="currentChange"
          >
            :pager-count="7">
          </el-pagination>
        </el-row>
      </div>
      <!-- 导入Excel弹框 -->
      <import-excel ref="iptExcel" @updateList="initData" />
      <!-- 员工关联角色弹框 -->
      <assign-role ref="assignRole" />
    </div>
  </div>
</template>

<script>
import { getDepartmentApi } from '@/api/department'
import { transListToTreeData } from '@/utils/index'
import { deleteEmployeeApi, exportEmployeeApi, getEmployeeListApi, infoEmployeeApi } from '@/api/employee'
import FileSaver from 'file-saver'
import importExcel from './components/importExcel.vue'
import assignRole from './components/assignRole.vue'
export default {
  name: 'Employee',
  components: {
    importExcel,
    assignRole
  },
  data() {
    return {
      depts: [],
      queryData: {
        keyword: '',
        departmentId: 1,
        page: 1,
        pagesize: 10
      },
      list: [],
      total: 0
    }
  },
  async created() {
    await this.getDepList() // 调用获取数据
    this.initData()
  },
  methods: {
    // 获取组织架构
    async getDepList() {
      // 请求函数（封装Api请求）
      const res = await getDepartmentApi()
      // 数据加工处理（使用工具函数整理成树）
      this.depts = transListToTreeData(res, 0)
      // 树的第一个节点高亮
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.depts[0].id)
      })
    },
    // 获取员工列表数据
    async initData() {
      const res = await getEmployeeListApi(this.queryData)
      // console.log(res)
      this.list = res.rows
      this.total = res.total
    },
    // 页码切换事件
    currentChange(val) {
      this.queryData.page = val
      this.initData()
    },
    // 树的高亮点击选中事件
    treeChange(val) {
      this.queryData.departmentId = val.id
      this.queryData.page = 1
      this.initData()
    },
    // 输入框内容变化搜素事件
    changeValue() {
      // 防抖优化
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.queryData.page = 1
        this.initData()
      }, 300)
    },
    // 导出
    async excelExport() {
      const res = await exportEmployeeApi()// 导出所有的员工接口
      // console.log(res)
      // const url = URL.createObjectURL(res)
      // const a = document.createElement('a')
      // a.href = url
      // a.download = '员工信息XXX.xlsx'
      // document.body.appendChild(a)
      // a.click()
      // document.body.removeChild(a)

      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    // 删除
    async confirmDel(id) {
      await deleteEmployeeApi(id)
      if (this.list.length === 1 && this.queryData.page > 1) {
        this.queryData.page--
      }
      this.initData()
      this.$message.success('删除员工成功')
    },
    // 打开角色弹框
    async openAssignRole(id) {
      // 发送回显API函数
      const res = await infoEmployeeApi(id)
      // 赋值
      this.$refs.assignRole.userId = id
      this.$refs.assignRole.checkRole = res.roleIds
      // 打开弹框
      this.$refs.assignRole.closeBox = true
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
